<template>
  <view class="detail-container">
    <!-- 地址信息 -->
    <view class="address-detail" @click="toAddress">
      <view v-if="formAddress.id" class="address-info">
        <uni-icons type="location" size="16" />
        <view class="address-item">
          <view class="address-buyer">
            <text>{{ formAddress.receiver_name }}</text>
            <text>{{ formAddress.receiver_mobile }}</text>
          </view>
          <view class="address-name">{{ formAddress.receiver_address }}</view>
        </view>
        <image src="/static/images/QuillChevronRight.png" mode="" class="address-icon" />
      </view>

      <view v-else class="address-info">
        <view class="address-warning">暂未配置收货地址</view>
        <image src="/static/images/QuillChevronRight.png" mode="" class="address-icon" />
      </view>
    </view>

    <!-- 卡券信息 -->
    <view class="order-detail">
      <view class="order-title">卡卷</view>
      <view class="order-info">
        <view class="order-item">
          <image :src="orderForm.image" class="order-image" mode="aspectFill" />
          <text class="order-name">{{ orderForm.name }}</text>
        </view>
      </view>
    </view>

    <!-- 商品选择 -->
    <view class="product-detail">
      <view class="product-title">
        <text>商品</text>
        <text class="warning">最多只能选择{{ orderForm.max_num }}个商品</text>
      </view>

      <view class="product-info">
        <view
          v-for="(item, index) in orderForm.products"
          :key="index"
          class="product-item"
          @tap="toggleProductSelection(index)"
        >
          <!-- 复选框 -->
          <checkbox
            class="custom-checkbox"
            :checked="item.checked"
            :disabled="isDisabled(item)"
            @click.stop="toggleProductSelection(index)"
          />

          <!-- 商品图片与信息 -->
          <image :src="item.picture" class="product-image" />
          <view class="product-readme">
            <text class="product-name">{{ item.product_name }}</text>
            <text class="product-count">x{{ item.num }}</text>
          </view>
        </view>
      </view>

      <!-- 下单备注 -->
      <view class="order-summary">
        <textarea
  v-model="orderForm.seller_memo"
  placeholder="请输入下单备注"
  class="value custom-textarea"
/>
      </view>
    </view>

    <!-- 占位视图 -->
    <view class="placeholder"></view>

    <!-- 提交按钮 -->
    <view class="submit-button">
      <button type="default" class="submit-button-style" @click="cancelOrder">取消</button>
  <button class="primary submit-button-style" @click="submitOrder">提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import uniIcons from "@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue";
import { onLoad } from "@dcloudio/uni-app";
import { fetchCardInfoApi } from "@/api/card";
import { createOrderApi } from "@/api/order";
import { fetchDefaultAddressApi } from "@/api/user";
import { userStore } from "@/stores/modules/userStore";
import { orderStore } from "@/stores/modules/orderStore"
import {showError, showSuccess, showWarning} from '@/utils/feedback'

const user = userStore();

const order = orderStore();
// 页面参数
const card_id = ref("");

// 表单数据
const orderForm = ref(order.orderForm);

// 收货地址
const formAddress = ref(order.formAddress);


/**
 * 获取卡券信息
 * @async
 */
const getCardInfo = async () => {
  // 订单缓存卡卷信息存在 并且 card_id等于 card_id 则不请求

  if (order.orderForm.card_id && order.orderForm.card_id == card_id.value) {
    return;
  }
  try {
    const res = await fetchCardInfoApi(card_id.value);
    if (res.code == 200) {
      orderForm.value = res.data;
      order.setOrderForm(res.data);
    } else {
      showError(res.message);
    }
  } catch (err) {
    console.error("获取卡券信息失败:", err);
    showError("获取卡券信息失败");
  }
};
/**
 * 获取默认地址
 * @async
 */
const getDefaultAddress = async () => {
  // 订单缓存地址存在 并且 id等于 缓存地址id 则不请求
  if (formAddress.value.id && formAddress.value.id == user.userInfo.shopAddressId) {
    return;
  }
  try {
    const res = await fetchDefaultAddressApi(user.userInfo.shopAddressId);
    if (res.code == 200) {
      formAddress.value = res.data;
      order.setAddress(res.data);
      user.setAddress(res.data.id);
    } else {
      showError(res.message || "获取地址失败");
    }
  } catch (error) {
    showError("获取地址失败");
  }
};

/**
 * 页面加载生命周期
 * @param {Object} options - 路由参数
 */
onLoad((options) => {
  if (!options?.card_id) {
    handleInvalidCardId();
    return;
  }

  card_id.value = options.card_id;
  initializePage();
});

/**
 * 初始化页面数据
 */
const initializePage = () => {
  getCardInfo();
  getDefaultAddress();
};

/**
 * 处理无效卡券ID
 */
const handleInvalidCardId = () => {
  showError("卡券不存在");
  setTimeout(() => {
    uni.switchTab({ url: "/pages/index/index" });
  }, 1500);
};

/**
 * 获取当前已勾选的商品数量
 * @returns {number}
 */
const getCheckedCount = () => {
  return orderForm.value.products.filter(p => p.checked).length;
};

/**
 * 切换商品选中状态
 * @param {number} index - 商品索引
 */
const toggleProductSelection = (index) => {
  const products = [...orderForm.value.products];
  const product = products[index];

  if (product.checked) {
    product.checked = false;
  } else {
    const currentCount = getCheckedCount();
    if (currentCount >= orderForm.value.max_num) {
      showWarning(`最多只能选择 ${orderForm.value.max_num} 个商品`);
      return;
    }
    product.checked = true;
  }

  orderForm.value.products = products;
};

/**
 * 判断是否应该禁用复选框（未选中且已达到最大数量）
 * @param {Object} item - 商品对象
 * @returns {boolean}
 */
const isDisabled = (item) => {
  const currentCount = getCheckedCount();
  return !item.checked && currentCount >= Number(orderForm.value.max_num);
};

/**
 * 提交订单
 * @async
 */
const submitOrder = async () => {
  if (!validateForm()) return;

  try {
    const payload = {
      ...orderForm.value,
      address_id: formAddress.value.id,
      products: orderForm.value.products.filter(p => p.checked),
    };

    const res = await createOrderApi(payload);

    console.log(res);
    
    if (res.code == 200) {
      showSuccess("订单提交成功");
      order.clearOrderData()
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/card/success?order_id=${res.data.id}`,
        });
      }, 1000);
    } else {
      showError(res.message || "提交失败");
    }
  } catch (error) {
    console.error("订单提交失败:", error);
    showError("提交失败");
  }
};

/**
 * 表单验证
 * @returns {boolean}
 */
const validateForm = () => {
  if (!formAddress.value?.id) {
    showWarning("请选择收货地址");
    return false;
  }

  const selectedProducts = orderForm.value.products.filter(p => p.checked);
  if (selectedProducts.length == 0) {
    showWarning("请选择商品");
    return false;
  }

  return true;
};

/**
 * 取消订单
 */
const cancelOrder = () => {
  order.clearOrderData()
  uni.switchTab({ url: "/pages/card/index" });
};

/**
 * 跳转到地址选择页
 */
const toAddress = () => {
  order.setOrderForm(orderForm.value)
  order.setAddress(formAddress.value)
  uni.navigateTo({
    url: `/pages/address/index?card_id=${card_id.value}`,
  });
};
</script>

<style scoped lang="scss">
.detail-container {
  display: flex;
  flex-direction: column;
}

.address-detail {
  background-color: #ffffff;
  color: #666666;
  border-radius: $uni-border-radius-base;
  margin-bottom: 20px;

  .address-info {
    display: flex;
    align-items: center;
    padding: 20px;

    .address-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 6px;
      padding: 10px;
    }

    .address-buyer {
      display: flex;
      gap: 10px;
      color: #333;
    }

    .address-name {
      font-size: 14px;
      color: #666666;
    }

    .address-warning {
      flex: 1;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .address-icon {
      width: 40px;
      height: 40px;
    }
  }
}

.order-detail {
  background-color: #fff;
  padding: 20px;
  border-radius: $uni-border-radius-base;
  margin-bottom: 20px;

  .order-title {
    font-size: 14px;
    color: #409eff;
    padding-bottom: 10px;
    border-bottom: 1px solid #409eff;
  }

  .order-item {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-top: 10px;
  }

  .order-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
  }

  .order-name {
    flex: 1;
    font-size: 14px;
    color: #333;
  }
}

.product-detail {
  background-color: #fff;
  padding: 20px;
  border-radius: $uni-border-radius-base;
  margin-bottom: 20px;

  .product-title {
    font-size: 14px;
    color: #409eff;
    padding-bottom: 10px;
    border-bottom: 1px solid #409eff;
    display: flex;
    justify-content: space-between;
  }

  .warning {
    color: #F7940C;
    font-size: 12px;
  }

  .product-info {
    padding-top: 10px;
  }

  .product-item {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 10px 0;
    border-bottom: 1px solid #eee;

    &:active {
      background-color: #f9f9f9;
    }

    .custom-checkbox {
      margin-right: 10px;
    }

    .product-image {
      width: 80px;
      height: 80px;
      border-radius: 8px;
    }

    .product-readme {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 6px;

      .product-name {
        font-size: 16px;
        color: #333;
      }
      
      .product-count {
        font-size: 16px;
        color: #333;
        text-align: right;
      }
    }
  }
}

.order-summary {
  padding-top: 10px;
  .value {
    font-size: 14px;
    padding: 20px;
    border: none;
    background-color: #f5f5f5;
    border-radius: 5px;
    height: 80px;
  }
  // 替换 textarea 选择器为 class 选择器
  .custom-textarea {
    width: auto;
  }
}

.placeholder {
  height: 60px;
}

.submit-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 999;
  // 替换 button 选择器为 class 选择器
  .submit-button-style {
    width: 48%;
    padding: 10px 20px;
    font-size: 16px;
  }

  .primary {
    background-color: $color-primary;
    color: #fff;
  }
}
</style>